package com.mars.oauth2.service.impl;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mars.oauth2.dto.SecurityUser;
import com.mars.oauth2.entity.AdminRole;
import com.mars.oauth2.entity.AdminUser;
import com.mars.oauth2.entity.Role;
import com.mars.oauth2.service.AdminRoleService;
import com.mars.oauth2.service.AdminUserService;
import com.mars.oauth2.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p> 自定义userDetailsService - 认证用户详情 </p>
 *
 * @author : zhengqing
 * @description :
 * @date : 2019/10/14 17:46
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private AdminUserService adminUserService;

  @Autowired
  private AdminRoleService adminRoleService;
  @Autowired
  private RoleService roleService;



    /***
     * 根据账号获取用户信息
     * @param username:
     * @return: org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中取出用户信息
        QueryWrapper<AdminUser> wrapper = new
                QueryWrapper<>();
        wrapper.eq("name",username);
        AdminUser adminUser = adminUserService.getOne(wrapper);
        // 判断用户是否存在
        if (adminUser==null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        QueryWrapper<AdminRole> queryWrapper = new QueryWrapper<>();
        List<AdminRole> adminRoles = adminRoleService.list(queryWrapper.eq("admin_id", adminUser.getId()));


        List<Integer> roleIds = adminRoles.stream().map(AdminRole::getRoleId).collect(Collectors.toList());
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.in("id", roleIds);
        List<Role> list = roleService.list(roleQueryWrapper);
        // 返回UserDetails实现类
        return new SecurityUser(adminUser, list);
    }

}
